package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    @Override
    public PageResult queryRecommendation(Long userId, Integer page, Integer pagesize) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(pagesize).skip(pagesize * (page - 1));
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);
        int count = recommendUsers.size();
        return new PageResult(page, pagesize, count, recommendUsers);
    }

    @Override
    public long queryScore(Long userId, Long id) {
        Query query = new Query(Criteria.where("recommendUserId").is(id).and("userId").is(userId));
        RecommendUser RU = mongoTemplate.findOne(query, RecommendUser.class);
        Long score = 0L;
        if (RU == null) {
            score = 80L;
        } else {
            score = RU.getScore() == null ? 80L : RU.getScore().longValue();
        }
        return score;
    }
}
